﻿<?php

require_once( dirname(__FILE__).'/../libs/bedmintonlib.php' );
 
function sendAcceptationMail( $mailTo, $customerId, & $outMessage )
{
    $iniReader = new IniReader();
    if (!$iniReader->iniValue( "smtpHost", $smtpHost ) ||
        !$iniReader->iniValue( "addressFromRegistracia", $addressFromRegistracia ) ||
        !$iniReader->iniValue( "addressRegistraciaPassword", $addressRegistraciaPassword ) ||  
        !$iniReader->iniValue( "acceptationAddress", $acceptationAddress ))
    {
        $outMessage = "Failed to read ini value";
        return false;
    }

    $from =  "Registrácia BBC";
    $to = "Vážený zákazník";
    $subjectStr = "Potvrdenie registrácie";
    $bodyStr = "Pre potvrdenie vašej registrácie kliknite na nasledujúci link ";
    if (isEnglish())
    {
        $from =  "Registration BBC";
        $to = "Dear customer";
        $subjectStr = "Confirm registration";
        $bodyStr = "Please click on the link to confirm your registration ";
    }

    $bodyStr .=  $acceptationAddress . "&customerId=" . $customerId;
    
    $mail = new PHPMailer( true );
    $mail->IsSMTP();
    try 
    {
        $mail->CharSet    = "UTF-8";
        $mail->Host       = $smtpHost; // SMTP server
        $mail->SMTPAuth   = true;                  // enable SMTP authentication
        $mail->Port       = 25;                    // set the SMTP port for the GMAIL server
        $mail->Username   = $addressFromRegistracia; // SMTP account username
        $mail->Password   = $addressRegistraciaPassword;        // SMTP account password
        $mail->AddAddress( $mailTo, $to );
        $mail->SetFrom( $addressFromRegistracia, $from );
        $mail->Subject = $subjectStr;
        $mail->Body = $bodyStr;
    
        $mail->Send();
        return true;
    } 
    catch (phpmailerException $e) 
    {
        $outMessage = $e->errorMessage();
        logError( __FUNCTION__ . ": Unable to send mail $outMessage" );
        return false;
    } 
    catch (Exception $e) 
    {
        $outMessage = $e->getMessage();
        logError( __FUNCTION__ . ": Unable to send mail $outMessage" );
        return false;
    }

    return false;
}

function registerNewUser( & $outMessage )
{    
    $customer = new Customer();
    if (! $customer->fromPost())
    {
        $outMessage = "Unable to read customer from post data";
        return false;
    }
  
    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        $outMessage = $db->getErrorStr();
        return false;
    }
    
    // funkcia na zistenie, ci uz pouzivatel neexistuje

    try
    {
        $statement = $dbConnection->prepare( "SELECT nextval('customersequence')" );
        $statement->execute();
        $obj= $statement->fetch( PDO::FETCH_OBJ );
        if (! $obj)
        {
            $outMessage = "Unknown error with id";
            return false;
        }
        
        $isCustomerEnglishSpeaking = isEnglish();
        $customer->id = $obj->nextval;
        $customer->state = 0;
        $statement = $dbConnection->prepare( "INSERT INTO customers ( id, sex, name, namenodiacritics, surname, surnamenodiacritics, passwordhash, passwordsalt, emailaddress, mobilphone, state, credits, isenglish, registrationdate ) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now() )" );
        
        $statement->bindParam( 1, $customer->id, PDO::PARAM_INT );
        $statement->bindParam( 2, $customer->sex, is_null( $customer->sex ) ? PDO::PARAM_NULL : PDO::PARAM_INT );
        $statement->bindParam( 3, $customer->name, PDO::PARAM_STR );
        $statement->bindParam( 4, $customer->namenodiacritics, PDO::PARAM_STR );
        $statement->bindParam( 5, $customer->surname, PDO::PARAM_STR );
        $statement->bindParam( 6, $customer->surnamenodiacritics, PDO::PARAM_STR );
        $statement->bindParam( 7, $customer->passwordhash, PDO::PARAM_STR );
        $statement->bindParam( 8, $customer->passwordsalt, PDO::PARAM_STR );
        $statement->bindParam( 9, $customer->emailaddress, PDO::PARAM_STR );
        $statement->bindParam( 10, $customer->mobilphone, is_null( $customer->mobilphone ) ? PDO::PARAM_NULL : PDO::PARAM_STR );
        $statement->bindParam( 11, $customer->state, PDO::PARAM_INT );
        $statement->bindParam( 12, $customer->credits, PDO::PARAM_INT );
        $statement->bindParam( 13, $isCustomerEnglishSpeaking, $isCustomerEnglishSpeaking == 0 ? PDO::PARAM_NULL : PDO::PARAM_INT );

        $statement->execute();
    }
    catch(PDOException $e)
    {
        $outMessage = $e->getMessage();
        return false;
    }
    
    if (! sendAcceptationMail( $customer->emailaddress, $customer->id, $outMessage ))
        return false;
  
    $db->commit();

    WebStat::logUserRegistered( $customer->emailaddress );
    logInfo( "New customer with email $customer->emailaddress was registered", LOG_INFO_USER_REGISTERED );
    $outMessage = isEnglish() ? "You were registered. Please confirm your registration when by clicking on the address which was sent on your email." : "Vaša registrácia prebehla úspešne. Pre potvrdenie registrácie kliknite na odkaz, ktorý bol poslaný na vašu emailovú adresu.";
    return true;
}

function updateUserState( & $dbConnection  )
{
    $statement = $dbConnection->prepare( "UPDATE customers SET state = 1 WHERE state = ? AND id = ?" );
    $statement->bindValue( 1, 0, PDO::PARAM_INT );
    $statement->bindParam( 2, $_GET[ 'customerId' ], PDO::PARAM_INT );  
    $statement->execute();
    $rowsCount = $statement->rowCount();
    return ( $rowsCount == 1 );
}

function acceptUser( $customerId, & $outMessage )
{
    $db = Db::db();
    $dbConnection = $db->connection();
    if (is_null( $dbConnection ))
    {
        $outMessage = $db->getErrorStr();
        return;
    }
    
    $state = 0;
    try
    {
        $statement = $dbConnection->prepare( "SELECT state from customers WHERE id = ?" );
        $statement->bindParam( 1, $customerId, PDO::PARAM_INT );
        $statement->execute();
        $obj = $statement->fetch( PDO::FETCH_OBJ );
        if (! $obj)
        {
            $outMessage = isEnglish() ? "Null obj" : "Prázdny objekt";
            return;
        }

        switch ($obj->state)
        {
            case 0: // NotConfirmed;
                if (updateUserState( $dbConnection ) && $db->commit())
                {
                    $outMessage = isEnglish() ? "The confirmation of your registration was accepted." : "Potvrdenie vašej registrácie prebehlo úspešne.";
                    return true;
                }
                else
                {
                    $outMessage = isEnglish() ? "Activation error" : "Chyba pri aktivácii";
                }
                return;

            case 1: // Activ;
                $outMessage = isEnglish() ? "You have been already activated." : "Už ste boli aktivovaný.";
                return false;

            case 2: // Blocked;
                $outMessage = isEnglish() ? "You were blocked by Administrator." : "Váš účet bol zablokovaný administrátorom systému.";
                return false;

            default:
                $outMessage = isEnglish() ? "Unknown state" : "Neznámy stav";
                return false;
        }
    }
    
    catch(PDOException $e)
    {
        $outMessage = isEnglish() ? "Error when selecting state." : "Chyba pri výbere dát";
        return false;
    }
    
    return true;
}

$outMessage = "";
$returnValue = false;
if (isset( $_GET[ 'customerId' ] ))
{
    $returnValue = acceptUser( $_GET[ 'customerId' ], $outMessage );
}
else
{
    $returnValue = registerNewUser( $outMessage );
}

if ($returnValue)
{
    showInfo( $outMessage );
}
else
{
    showError( $outMessage );
}
?>
